package com.ihr360.job.core.item.support;

import com.ihr360.job.core.item.ItemReader;
import com.ihr360.job.core.item.ParseException;
import com.ihr360.job.core.item.UnexpectedInputException;
import org.springframework.util.Assert;

import java.util.Iterator;

/**
 * An {@link ItemReader} that pulls data from a {@link Iterator} or
 * {@link Iterable} using the constructors.
 *
 * @author Juliusz Brzostek
 * @author Dave Syer
 */
public class IteratorItemReader<T> implements ItemReader<T> {

    /**
     * Internal iterator
     */
    private Iterator<T> iterator;

    /**
     * Construct a new reader from this iterable (could be a collection), by
     * extracting an instance of {@link Iterator} from it.
     *
     * @param iterable in instance of {@link Iterable}
     * @see Iterable#iterator()
     */
    public IteratorItemReader(Iterable<T> iterable) {
        setIterator(iterable);
    }

    /**
     * Construct a new reader from this iterator directly.
     *
     * @param iterator an instance of {@link Iterator}
     */
    public IteratorItemReader(Iterator<T> iterator) {
        Assert.notNull(iterator, "Iterator argument cannot be null!");
        this.iterator = iterator;
    }

    public IteratorItemReader() {
    }

    protected void setIterator(Iterable<T> iterable) {
        Assert.notNull(iterable, "Iterable argument cannot be null!");
        this.iterator = iterable.iterator();
    }

    /**
     * Implementation of {@link ItemReader#read()} that just iterates over the
     * iterator provided.
     */
    @Override
    public T read() throws Exception, UnexpectedInputException, ParseException {
        if (iterator.hasNext())
            return iterator.next();
        else
            return null; // end of data
    }

}
